package regexp;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author DCSGO
 * @version 1.0
 * Matcher 常用方法
 */
public class MatcherMethod {
    public static void main(String[] args) {
        Pattern pattern = Pattern.compile("\\w+");
        Matcher matcher = pattern.matcher("dcs123");
        // matches 整体匹配
        System.out.println(matcher.matches());//true

        // start end 当前匹配到的分组的开始和结束位置 可用于字符串的拼接
        Pattern pattern1 = Pattern.compile("(\\d{2})");
        String input = "01234";
        Matcher matcher1 = pattern1.matcher(input);
        while (matcher1.find()) {
            System.out.println("------------");
            int start = matcher1.start();
            int end = matcher1.end();
            System.out.println(start + " " + end);
            System.out.println(input.substring(start, end));
        }
        /*
         * ------------
         * 0 2
         * 01
         * ------------
         * 2 4
         * 23
         *
         * 进程已结束，退出代码为 0
         */

        // replaceAll 通过正则表达式进行字符替换(返回替换后的字符串 原字符串不变)
        Pattern pattern2 = Pattern.compile("baidu");
        String input2 = "baidu.com baidu.edu baidu.org";
        Matcher matcher2 = pattern2.matcher(input2);
        String newStr = matcher2.replaceAll("百度");
        System.out.println("oldStr: " + input2);//oldStr: baidu.com baidu.edu baidu.org
        System.out.println("newStr: " + newStr);//newStr: 百度.com 百度.edu 百度.org
    }
}
